<?php
namespace app\common\wechat;

/**
 * 微信oAuth认证
 */
class Wxauth
{
    private $options;
    private $state;
    public $openid;
    public $wxuser;

    public function __construct($options, $scope,$state='')
    {
        $this->options = $options;
        $this->state = $state;
        if ($scope == "userinfo") {
            $this->wxoauthUserInfo();
        } else {
            $this->wxoauthBase();
        }
    }

    public function wxoauthUserInfo()
    {
        $scope = 'snsapi_userinfo';

        $code = isset($_GET['code']) ? $_GET['code'] : '';
        $token_time = session('?token_time') ? session('token_time') : 0;
        if (!$code && session('?open_id') && session('?wxuser') &&
            session('?user_token') && $token_time > time() - 3600) {
            if (!$this->wxuser) {
                $this->wxuser = session('wxuser');
            }
            $this->openid = session('open_id');
            return $this->openid;
        } else {
            $options = array(
                'token' => $this->options["token"], //填写你设定的key
                'appid' => $this->options["appid"], //填写高级调用功能的app id
                'appsecret' => $this->options["appsecret"], //填写高级调用功能的密钥
            );
            $we_obj = new TPWechat($options);
            if ($code) {
                $json = $we_obj->getOauthAccessToken();
                if (!$json) {
                    die('获取用户授权失败，请重新确认');
                }

                $this->openid = $json["openid"];
                session('open_id', $json["openid"]);
                $access_token = $json['access_token'];
                session('user_token', $access_token);
                session('token_time', time());

                $userinfo = $we_obj->getUserInfo($this->openid);
                if ($userinfo && !empty($userinfo['nickname'])) {
                    $this->wxuser = array(
                        'open_id' => $this->openid,
                        'nickname' => $userinfo['nickname'],
                        'sex' => intval($userinfo['sex']),
                        'location' => $userinfo['province'] . '-' . $userinfo['city'],
                        'avatar' => $userinfo['headimgurl'],
                    );
                } elseif (strstr($json['scope'], 'snsapi_userinfo') !== false) {
                    $userinfo = $we_obj->getOauthUserinfo($access_token, $this->openid);
                    if ($userinfo && !empty($userinfo['nickname'])) {
                        $this->wxuser = array(
                            'open_id' => $this->openid,
                            'nickname' => $userinfo['nickname'],
                            'sex' => intval($userinfo['sex']),
                            'location' => $userinfo['province'] . '-' . $userinfo['city'],
                            'avatar' => $userinfo['headimgurl'],
                        );
                    } 
                }
                if ($this->wxuser) {
                    session('wxuser', $this->wxuser);
                }
                return $this->openid;
            }

            $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $oauth_url = $we_obj->getOauthRedirect($url, $this->state, $scope);
            header('Location: ' . $oauth_url);
            die;
        }
    }

    public function wxoauthBase()
    {
        $scope = 'snsapi_base';
        $code = isset($_GET['code']) ? $_GET['code'] : '';
        $token_time = session('?token_time') ? session('token_time') : 0;
        if (session('?open_id') && session('?user_token') && $token_time > time() - 3600) {
            $this->openid = session('open_id');
            return $this->openid;
        } else {
            $options = array(
                'token' => $this->options["token"], //填写你设定的key
                'appid' => $this->options["appid"], //填写高级调用功能的app id
                'appsecret' => $this->options["appsecret"], //填写高级调用功能的密钥
            );
            $we_obj = new TPWechat($options);
            if ($code) {
                $json = $we_obj->getOauthAccessToken();
                if (!$json) {
                    die('获取用户授权失败，请重新确认');
                }
                $this->openid = $json["openid"];
                session('open_id', $json["openid"]);
                $access_token = $json['access_token'];
                session('user_token', $access_token);
                session('token_time', time());
                return $this->openid;
            }
            $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $oauth_url = $we_obj->getOauthRedirect($url, $this->state, $scope);
            header('Location: ' . $oauth_url);
            die;
        }
    }
}
